package cn.nucun.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * http 工具类
 *
 * @author chen
 */
public class HttpUtils {

    /**
     * POST请求-默认请求头
     *
     * @param json 请求JSON对象
     * @param url  请求地址
     * @return 请求所响应的内容串
     */
    public static String post(JSONObject json, String url) {
        return post(json, null, url);
    }

    /**
     * POST请求
     *
     * @param json      请求JSON对象
     * @param headerMap 请求头组
     * @param url       请求地址
     * @return 请求所响应的内容串
     */
    public static String post(JSONObject json, Map<String, String> headerMap, String url) {
        String result = "";
        HttpPost post = new HttpPost(url);
        try {
            if (headerMap != null) {
                Set<Map.Entry<String, String>> set = headerMap.entrySet();
                for (Map.Entry<String, String> entry : set) {
                    post.setHeader(entry.getKey(), entry.getValue());
                }
            } else {
                post.addHeader("Authorization", "Basic YWRtaW46");
                post.setHeader("Content-Type", "application/json;charset=utf-8");
            }
            CloseableHttpClient httpClient = HttpClients.createDefault();
            StringEntity postingString = new StringEntity(json.toString(), "utf-8");
            post.setEntity(postingString);
            HttpResponse response = httpClient.execute(post);

            InputStream in = response.getEntity().getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
            StringBuilder strber = new StringBuilder();
            String line = null;
            while ((line = br.readLine()) != null) {
                strber.append(line + '\n');
            }
            br.close();
            in.close();
            result = strber.toString();
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                result = "服务器异常";
            }
        } catch (Exception e) {
            System.out.println("请求异常");
            throw new RuntimeException(e);
        } finally {
            post.abort();
        }
        return result;
    }

    /**
     * GET请求
     *
     * @param paramMap  请求实体组
     * @param headerMap 请求头组
     * @param url       请求地址
     * @return 请求所响应的内容串
     */
    public static String get(Map<String, String> paramMap, Map<String, String> headerMap, String url) {
        String result = "";
        HttpGet get = new HttpGet(url);
        try {
            if (headerMap != null) {
                Set<Map.Entry<String, String>> set = headerMap.entrySet();
                for (Map.Entry<String, String> entry : set) {
                    get.setHeader(entry.getKey(), entry.getValue());
                }
            } else {
                get.setHeader("Connection", "keep-alive");
                get.setHeader("Cache-Control", "no-cache");
                get.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat");
                get.setHeader("content-type", "application/json; charset=utf-8");
                get.setHeader("Accept-Encoding", "gzip, deflate, br");
                get.setHeader("Accept", "application/json, text/javascript, */*; q=0.01");
                get.setHeader("Accept-Language", "zh-CN");
            }
            CloseableHttpClient httpClient = HttpClients.createDefault();
            List<NameValuePair> params = setHttpParams(paramMap);
            String param = URLEncodedUtils.format(params, "UTF-8");
            get.setURI(URI.create(url + "?" + param));
            HttpResponse response = httpClient.execute(get);
            result = getHttpEntityContent(response);

            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                result = "服务器异常";
            }
        } catch (Exception e) {
            System.out.println("请求异常");
            throw new RuntimeException(e);
        } finally {
            get.abort();
        }
        return result;
    }

    /**
     * GET请求-默认请求头
     *
     * @param paramMap 请求实体组
     * @param url      请求地址
     * @return 请求所响应的内容串
     */
    public static String get(Map<String, String> paramMap, String url) {
        return get(paramMap, null, url);
    }

    public static List<NameValuePair> setHttpParams(Map<String, String> paramMap) {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        Set<Map.Entry<String, String>> set = paramMap.entrySet();
        for (Map.Entry<String, String> entry : set) {
            params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        return params;
    }

    public static String getHttpEntityContent(HttpResponse response) throws UnsupportedOperationException, IOException {
        String result = "";
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream in = entity.getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
            StringBuilder strber = new StringBuilder();
            String line = null;
            while ((line = br.readLine()) != null) {
                strber.append(line + '\n');
            }
            br.close();
            in.close();
            result = strber.toString();
        }

        return result;
    }
}

